package cn.edu.xmist.supermarket.zpc.controller;

import cn.edu.xmist.supermarket.zpc.Vars;
import cn.edu.xmist.supermarket.zpc.entity.ProductPO;
import cn.edu.xmist.supermarket.zpc.service.ProductService;
import cn.edu.xmist.supermarket.zpc.util.ObjtoLayJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品控制器
 *
 * @author zpc
 */
@RestController
@RequestMapping("/product")
public class GoodsController {

    /**
     * 表字段映射
     */
    public static final String[] COLUMNS = {"id", "name", "price", "num", "houseCode", "supplierCode"};

    @Autowired
    private ProductService productService;

    /**
     * 商品列表
     *
     * @param page  分页页码
     * @param limit 分页大小
     * @return
     * @throws Exception
     */
    @RequestMapping("/list")
    public String list(Integer page, Integer limit) throws Exception {
        List<ProductPO> list = productService.list();
        List<ProductPO> pageList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if (i >= (page - 1) * limit && i < page * limit) {
                pageList.add(list.get(i));
            }
        }
        return ObjtoLayJson.ListtoJson(pageList, COLUMNS);
    }

    /**
     * 分页查询
     *
     * @param page
     * @param limit
     * @param product
     * @return
     * @throws Exception
     */
    @RequestMapping("/pageList")
    public String pageList(Integer page, Integer limit, ProductPO product) throws Exception {
        System.out.println(product.toString() + "1111");
        List<ProductPO> pageList = productService.selectPage(product, page, limit);
        String[] column = {
                "id", "name", "price", "num", "houseCode", "supplierCode", "houseName", "supplierName"
        };
        return ObjtoLayJson.ListtoJson(pageList, column);
    }

    /**
     * 保存或更新商品
     *
     * @param product
     * @return
     */
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(ProductPO product) {
        Boolean flag = productService.saveOrUpdate(product);
        return Vars.SUCCESS;
    }

    /**
     * 删除商品
     *
     * @param id
     * @return
     */
    @RequestMapping("/deleteById")
    public String deleteById(Long id) {
        Boolean flag = productService.removeById(id);
        return Vars.SUCCESS;
    }
}
